package sdufe.lele;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import sdufe.lele.Interceptor.ApiAuthenticating;
import sdufe.lele.filter.corsFilter;

import javax.servlet.Filter;
import java.text.SimpleDateFormat;

@SpringBootApplication
@EnableScheduling
public class FfmsApplication extends WebMvcConfigurerAdapter{

    public static void main(String[] args) {
        SpringApplication.run(FfmsApplication.class, args);
    }

    /**
     * 配置拦截器
     */
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(apiAuthenticating()).addPathPatterns("/**");
    }
    @Bean
    public ApiAuthenticating apiAuthenticating() {
        return new ApiAuthenticating();
    }


    /**
     * 配置Filter
     * @return
     */
    @Bean
    public FilterRegistrationBean crossOriginFilterRegistration() {
        FilterRegistrationBean registration = new FilterRegistrationBean();
        registration.setFilter(crossOriginFilter());
        registration.addUrlPatterns("/*");
        registration.setName("crossOriginFilter");
        registration.addInitParameter("allowOrigin", "*");
        registration.setOrder(1);
        return registration;
    }
    @Bean(name = "crossOriginFilter")
    public Filter crossOriginFilter() {
        return new corsFilter();
    }


    @Autowired()
    public void configeJackson(ObjectMapper jackson2ObjectMapper) {

        jackson2ObjectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd"));
        jackson2ObjectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);

        jackson2ObjectMapper.enable(SerializationFeature.WRITE_ENUMS_USING_INDEX);

        jackson2ObjectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
    }

    /**
     * 用于处理编码问题
     * @return
     */
    @Bean
    public Filter characterEncodingFilter() {
        CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
        characterEncodingFilter.setEncoding("UTF-8");
        characterEncodingFilter.setForceEncoding(true);
        return characterEncodingFilter;
    }







}
